// Copyright (c) 2022 CHANGLEI. All rights reserved.

import 'package:aircraft_war/bloc/bloc_listenable.dart';
import 'package:aircraft_war/components/main_game.dart';
import 'package:aircraft_war/foundation/sounds.dart';
import 'package:bloc/bloc.dart';
import 'package:flame/components.dart';
import 'package:flame/flame.dart';
import 'package:flutter/services.dart';

/// Created by changlei on 2022/5/18.
///
/// 游戏的全局状态
class GameStateCubit extends Cubit<GameState> {
  /// 游戏的全局状态
  GameStateCubit({
    GameState state = GameState.idle,
  }) : super(state) {
    setup();
  }

  /// 游戏实例
  late final game = MainGame(this);

  /// 是否正在运行
  bool get isRunning => state == GameState.running;

  /// 空闲中
  void setup() {
    Flame.device.setPortraitUpOnly();
    Sounds.bgm.setup();
    Sounds.loadCaches();
    emit(GameState.idle);
  }

  /// 等待中
  void pending() {
    Sounds.bgm.pending();
    emit(GameState.pending);
  }

  /// 运行
  void run() {
    Sounds.bgm.run();
    emit(GameState.running);
  }

  /// 暂停中
  void pause() {
    Sounds.bgm.pause();
    emit(GameState.pausing);
  }

  /// 已结束
  void stop() {
    Sounds.bgm.stop();
    Sounds.disposePlayers();
    emit(GameState.stopped);
  }

  @override
  Future<void> close() {
    Flame.device.setOrientations(DeviceOrientation.values);
    Sounds.bgm.dispose();
    Sounds.clearCaches();
    return super.close();
  }
}

/// 状态
enum GameState {
  /// 空闲中
  idle,

  /// 等待中
  pending,

  /// 运行中
  running,

  /// 暂停中
  pausing,

  /// 已结束
  stopped,
}

/// [PositionComponent]
abstract class GameStatePositionComponent extends PositionComponent
    with BlocListenable<GameStateCubit, GameState>, HasGameRef<MainGame> {
  /// [PositionComponent]
  GameStatePositionComponent({
    super.position,
    super.size,
    super.scale,
    super.angle,
    super.anchor,
    super.children,
    super.priority,
  });
}

/// 扩展
extension PositionComponents on PositionComponent {
  /// 判断是否包含
  bool containsOfParent(Vector2 position) {
    return parent?.containsPoint(position - (anchor.toVector2()..multiply(size))) == true;
  }
}
